const _ = require('lodash');
const async = require('async');
const Ajv = require('ajv');
const services = require('../services');
const enums = require('../enums');

const ajv = new Ajv({ coerceTypes: true });
const commonService = services.common;

module.exports = (WfRunInstance) => {
  WfRunInstance.observe('before save', (ctx, callback) => {
    let data = {};
        if (ctx.isNewInstance && ctx.instance) data = ctx.instance.__data; // eslint-disable-line
    else if (ctx.instance) data = ctx.instance.data;
    else if (ctx.data) data = ctx.data;
    if (data.formStatus != enums.formStatus.submitted) return callback();
    const { WfForm: formModel } = commonService.getModels();
    const getForm = (next) => {
      commonService.getDetail(formModel, { where: { id: data.formId } }, next);
    };
    const verifyData = (form, next) => {
      ajv.validate(form.verify, data.formDetail);
      if (_.isEmpty(ajv.errors)) {
        return next(null);
      }
      console.log(ajv.errors);
      return next(commonService.getError(enums.errorCode.badRequest, ajv.errors));
    };
    async.waterfall([getForm, verifyData], callback);
  });
};
